package Search_Thermostat;
import java.io.*;	
import java.net.*;
import java.util.*;

class MulticastServerThread extends Thread{
private long FIVE_SECONDS = 500;
protected BufferedReader in = null;
protected boolean moreQuotes = true;
MulticastSocket socket=null;// = new MulticastSocket(4446);

String BuildSearchRequest() {
       String ret = "TYPE: WM-DISCOVER" + "\r\n"
                    + "VERSION: 1.0" + "\r\n"
         		+"SERVICES: com.marvell.wm.system*"+"\r\n\r\n";
       return ret;
}
String BuildST() {
       String ret = "ST:";
              ret += "ssdp:all";
              ret += "\r\n";
              return ret;
}
	 

    public MulticastServerThread(String name) throws IOException {
        super(name);
        socket = new MulticastSocket(1901);
    }
	public MulticastServerThread() throws IOException {
        this("MulticastServerThread");
    }
 public String find() {
    while (moreQuotes) {
        try {
            byte[] buf =new byte[4096];
            
            String dString = null;
            dString = BuildSearchRequest();
            buf = dString.getBytes();

            InetAddress group = InetAddress.getByName(
                                            "239.255.255.250");
            DatagramPacket packet;
            packet =	 new DatagramPacket(buf, buf.length, 
                                        group, 1900);
            socket.send(packet);
			System.out.println("SENT"+" "+InetAddress.getLocalHost());
			 moreQuotes = false;
			 DatagramPacket packet1;
				packet1 = new DatagramPacket(buf, buf.length);
			socket.receive(packet1);
           String received = new String(packet.getData(), 0, packet.getLength());
		   String url=packet1.getAddress().toString();
           System.out.println(received+"\n"+url);   
            try {
			if(!url.equals(""))
			{
				socket.close();
				return url;
			}
			System.out.println("SLEEP-5 SECONDS");
                sleep(FIVE_SECONDS);
            } catch (InterruptedException e) { e.printStackTrace();}
        } catch (IOException e) {
            e.printStackTrace();
            moreQuotes = false;
			socket.close();
			return "";
        }
    }
	return "";
}
	
}

public class Search_Thermostat {
    public static void main(String[] args) throws IOException {
        
    }
	public String find() throws IOException
	{
		return new MulticastServerThread().find();
	}
}
